package com.cloud.auth.component;

import cn.hutool.json.JSONUtil;
import com.cloud.common.base.Result;
import com.cloud.common.enums.ResultEnum;
import com.cloud.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

import java.io.Serializable;


/**
 * 授权服务器 异常统一处理
 * @author Aijm
 * @since 2019/5/16
 */
@Slf4j
public class Auth2ResponseExceptionTranslator implements WebResponseExceptionTranslator {

    @Override
    public ResponseEntity translate(Exception e) {
        log.error("异常:{}", e);
        if (e instanceof InvalidTokenException){
            Result<Serializable> error = Result.error(ResultEnum.TOKEN_PAST);
            return new ResponseEntity(JSONUtil.toJsonStr(error), HttpStatus.OK);
        }
        // 反射获取不到异常
        Throwable cause = e.getCause();
        if (cause instanceof BaseException) {
            Result<Serializable> error = Result.error(((BaseException) cause).getCode(), cause.getMessage());
            return new ResponseEntity(JSONUtil.toJsonStr(error), HttpStatus.OK);
        }
        return new ResponseEntity(Result.error(e.getMessage()), HttpStatus.OK);
    }
}
